package com.sbl.dao.impl;

import com.sbl.dao.IAccountDaoDatabaseXML;
import com.sbl.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import java.sql.SQLException;
import java.util.List;

/**
 * 类名都不规范，仅仅为了自己看的时候方便
 *
 *   持久层具体实现
 *         1. xml配置的方式使用的这个类进行测试
 *         2. 注解Java配置类的方式，为了简单方便，也是用了这个类做的测试
 */

//这里面的值，用于注入对象时候，bean注入
@Repository("accountDaoDatabaseXML")
public class AccountDaoDatabaseXMLImpl implements IAccountDaoDatabaseXML {


    // 当有多个实现的时候，变量名为bean的id ，就可以了
    //推测 QueryRunner 有多个实现子类（有疑问，好像只有一个）
    @Autowired
    private QueryRunner runner;

    /**
     *  BeanListHandler：将结果集中每一条记录装到指定的javaBean中，将这些JavaBean再
     *  封装到List集合中
     *
     * @return
     */
    public List<Account> findAllAccount()  {
        try {
            return  runner.query("select * from account",new BeanListHandler<Account>(Account.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public Account findOneAccountById(Integer id) {
        try{
            return runner.query("select * from account where id = ? ",new BeanHandler<Account>(Account.class),id);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void saveAccount(Account account) {
        try{
            runner.update("insert into account(name,money)values(?,?)",account.getName(),account.getMoney());
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void updateAccount(Account account) {
        try{
            runner.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void deleteAccount(Integer accountId) {
        try{
            runner.update("delete from account where id=?",accountId);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
